<template>
  <div class="container p-6">
    <!-- 搜索区域 -->
    <div class="mb-4 flex items-center space-x-4">
      <el-input
        v-model="searchParams.name"
        placeholder="输入姓名"
        class="!w-[200px]"
        clearable
        @input="handleAutoSearch"
        @clear="handleAutoSearch"
        size="large"
      />
      <el-select
        v-model="searchParams.gradeId"
        placeholder="选择或搜索班级"
        class="!w-[200px]"
        clearable
        @change="handleAutoSearch"
        size="large"
      >
        <el-option
          v-for="item in gradeOptions"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="handleAdd" size="large">添加</el-button>
      <el-button @click="handleImport" size="large">导入</el-button>
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
        size="large"
        >批量删除</el-button
      >
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        prop="idNu"
        label="身份证号码"
        min-width="140"
        align="center"
      />
      <el-table-column
        prop="name"
        label="姓名"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="phone"
        label="手机号"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="gradeName"
        label="班级"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        min-width="180"
        align="center"
      />
      <el-table-column label="操作" fixed="right" width="120" align="center">
        <template #default="scope">
          <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ searchParams.total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="searchParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
          layout="prev, pager, next"
          :total="searchParams.total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="上传文件"
      width="500px"
      align-center
    >
      <el-upload
        class="upload-demo"
        drag
        action="/api/api/user/import?type=1"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        accept=".xlsx,.xls"
        :limit="1"
      >
        <div class="upload-content">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="upload-text">
            <p>将文件拖到此处，或<span class="text-primary">点击上传</span></p>
          </div>
          <div class="upload-tip mt-2 text-gray-500 text-sm">
            只能上传xls/xlsx文件，且不超过1500kb,大小为12kb
          </div>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDownloadTemplate"
            >下载模板</el-button
          >
          <el-button type="primary" @click="handleConfirmUpload"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 添加学生侧边栏 -->
    <el-drawer
      v-model="dialogVisible"
      :title="isEditMode ? '编辑学生' : '添加学生'"
      :modal="true"
      size="350px"
      :close-on-click-modal="false"
      direction="rtl"
      destroy-on-close
    >
      <template #default>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="drawer-form"
        >
          <el-form-item label="身份证号" prop="idNu">
            <el-input v-model="form.idNu" placeholder="请输入身份证号码" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话号码" />
          </el-form-item>
          <el-form-item label="班级" prop="gradeId">
            <el-select
              v-model="form.gradeId"
              placeholder="请选择班级"
              style="width: 100%"
            >
              <el-option
                v-for="item in gradeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import {
  getStudentList,
  addUser,
  getGradeList,
  editUser,
  deleteUser,
  batchDeleteUser,
} from '@/api/teacher/usermanage'

// 表格数据
const tableData = ref([])

// 分页相关
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 10,
  name: '',
  gradeId: '',
})

// 导入对话框
const importDialogVisible = ref(false)
const uploadHeaders = {
  Authorization: getToken(),
}

// 选中的行
const selectedRows = ref([])

// 弹窗显示控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentEditId = ref('')
// 表单ref
const formRef = ref()

// 表单数据
const form = reactive({
  idNu: '',
  name: '',
  phone: '',
  gradeId: '',
})

// 班级选项
const gradeOptions = ref([])

// 表单验证规则
const rules = {
  idNu: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号码',
      trigger: 'blur',
    },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  gradeId: [{ required: true, message: '请选择班级', trigger: 'change' }],
}

// 获取学生列表
const getStudentlist = async () => {
  const { data } = await getStudentList(searchParams)
  tableData.value = data.records
  searchParams.total = data.total
  searchParams.pageNum = data.current
  searchParams.pageSize = data.size
}

// 获取班级列表
const getGradelist = async () => {
  const { data } = await getGradeList()
  // 将班级列表转换为选项
  gradeOptions.value = data.records.map((item) => ({
    value: item?.id,
    label: item?.gradeName,
  }))
  // 过滤掉没有value的选项
  gradeOptions.value = gradeOptions.value.filter((item) => {
    if (item.value) {
      return item
    }
  })
}

// 自动搜索处理函数
const handleAutoSearch = () => {
  getStudentlist()
}

// 处理导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该学生吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 调用批量删除API，传递单个ID
        const { code, msg } = await batchDeleteUser([row.id])

        if (code == 0) {
          ElMessage.error('删除失败：' + msg)
          return
        }

        ElMessage.success('删除成功')
        getStudentlist()
      } catch (error) {
        console.error('删除出错：', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理文件上传成功
const handleUploadSuccess = (response) => {
  ElMessage.success('导入成功')
  importDialogVisible.value = false
  // TODO: 刷新表格数据
}

// 处理文件上传失败
const handleUploadError = () => {
  ElMessage.error('导入失败')
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  searchParams.pageSize = val
  // 修正函数名
  getStudentlist()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchParams.pageNum = val
  // TODO: 重新加载数据
  getStudentlist()
}

// 处理跳转页码
const jumpPage = ref('')
const handleJumpPage = () => {
  // TODO: 实现跳转逻辑
  searchParams.pageNum = jumpPage.value
  getStudentlist()
}

// 处理文件上传前的验证
const handleBeforeUpload = (file) => {
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
  const isLt1500kb = file.size / 1024 <= 1500

  if (!isExcel) {
    ElMessage.error('只能上传 xlsx/xls 格式的文件!')
    return false
  }
  if (!isLt1500kb) {
    ElMessage.error('文件大小不能超过 1500kb!')
    return false
  }

  return true
}

// 处理下载模板
const handleDownloadTemplate = () => {
  // 修改路径为正确的公共目录路径
  const a = document.createElement('a')
  a.href = '/template/ImportUserTemplate.xlsx'
  a.download = '导入用户模板.xlsx'
  // 障眼法藏起来a标签
  a.style.display = 'none'
  // 将a标签追加到文档对象中
  document.body.appendChild(a)
  // 模拟点击了<a>标签,会触发<a>标签的href的读取,浏览器就会自动下载了
  a.click()
  // 一次性的,用完就删除a标签
  a.remove()
}

// 处理确认上传
const handleConfirmUpload = () => {
  // TODO: 实现确认上传逻辑
  console.log('确认上传')
  importDialogVisible.value = false
}

// 打开添加弹窗
const handleAdd = () => {
  isEditMode.value = false
  dialogVisible.value = true

  // 先手动清空表单数据
  form.idNu = ''
  form.name = ''
  form.phone = ''
  form.gradeId = ''

  // 然后重置表单验证状态
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  currentEditId.value = row.id
  dialogVisible.value = true
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 明确指定每个字段的赋值，避免字段不匹配
  form.idNu = row.idNu || ''
  form.name = row.name || ''
  form.phone = row.phone || ''
  form.gradeId = row.gradeId || ''
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 这里添加提交到后端的逻辑
      const newStudent = {
        ...form,
        id: isEditMode.value ? currentEditId.value : undefined,
        roleId: 1,
        userType: 1,
      }
      const { code, data, msg } = isEditMode.value
        ? await editUser(newStudent)
        : await addUser(newStudent)
      if (code == 0) {
        ElMessage.error((isEditMode.value ? '修改' : '添加') + '失败：' + msg)
        return
      }

      ElMessage.success(isEditMode.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
      // 刷新表格数据
      getStudentlist()
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 获取所有选中行的ID
        const ids = selectedRows.value.map((row) => row.id)

        // 调用批量删除API
        const { code, msg } = await batchDeleteUser(ids)

        if (code == 0) {
          ElMessage.error('批量删除失败：' + msg)
          return
        }

        ElMessage.success('批量删除成功')
        // 刷新表格数据
        getStudentlist()
        // 清空选中
        selectedRows.value = []
      } catch (error) {
        console.error('批量删除出错：', error)
        ElMessage.error('批量删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 挂载
onMounted(() => {
  // 获取用户信息
  getStudentlist()
  // 获取班级信息
  getGradelist()
})
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

:deep(.el-table) {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
  }

  .el-table__header th {
    .cell {
      justify-content: center;
    }
  }

  .el-button {
    margin: 2px;
  }
}

// 上传区域样式
:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #e6e6e6;
  border-radius: 8px;

  &:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon--upload {
    font-size: 48px;
    color: #909399;
    margin-bottom: 12px;
  }

  .upload-text {
    color: #606266;
    font-size: 14px;
    text-align: center;

    .text-primary {
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}

// 分页样式
:deep(.el-pagination) {
  .el-pagination__total {
    margin-right: 16px;
  }

  .el-pagination__sizes {
    margin-right: 16px;
  }

  .el-pager li {
    background-color: transparent;

    &.is-active {
      background-color: var(--el-color-primary);
      color: white;
    }
  }

  .btn-prev,
  .btn-next {
    background-color: transparent;
  }

  .el-input__inner {
    text-align: center;
    padding: 0 5px;
  }
}

// 下拉选择框样式
:deep(.el-select) {
  .el-input__wrapper {
    background-color: transparent;
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 20px;
  }
}

// 抽屉表单样式
:deep(.el-drawer__body) {
  padding: 20px;

  .drawer-form {
    height: calc(100% - 60px);
    overflow-y: auto;
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  background: white;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
